<?php
/**
 * @file search.php
 * @author LJ (liangjian@haibao.com)
 * @date 2015年12月21日 下午4:11:30
 * @brief 
 */
namespace haibao\app\data;

class Search extends \haibao\app\data\BaseMysql{
    
    const PAGE_SIZE = 20;

    public function __construct(){
        parent::__construct('\haibao\app\model\data\Search');
    }
    
    /**
     * 自动提示列表
     */
    public function autoList($keyword){
        $this->saveSearchRecod($keyword);
        $cache = new \haibao\app\cache\Search();
        $retResult = (array)$cache->getAutoStar($keyword);
        $retResult = array();
        if(!$retResult){
            $result = $this->dbApp()->query('select * from Search where TagType in(%s) and ArticleCount>0 and (Keyword like %s or KeywordEN like %s) order by ArticleCount desc limit 10', array(
                \haibao\app\model\data\Search::KEYWORD_TYPE_STAR, '%'.$keyword.'%', '%'.$keyword.'%'
            ));
            while ($result->fetch_assoc()) {
                array_push($retResult, array(
                    'tagId' => $result->getData('RecordId'),
                    'tagType' => $result->getData('TagType'),
                    'keyword' => $result->getData('Keyword'),
                    'keywordEn' => $result->getData('KeywordEN'),
                )); 
            }
            $retResult && $cache->setAutoStar($keyword, $retResult);
        }
        return $retResult;
    }
    
    /**
     * 根据关键字搜索文章结果列表
     */
    public function searchArticle($keyword, $page){
        $this->saveSearchRecod($keyword);
        $cache = new \haibao\app\cache\Search();
        $cacheKey = $keyword.'_'.$page;
        $searchList = (array)$cache->getSearchList($cacheKey);
        if(!$searchList){
            $search = $this->dbApp()->query('select TagType,RecordId from Search where TagType in (%s,%s) and (Keyword like %s or KeywordEN like %s)', array(
                \haibao\app\model\data\Search::KEYWORD_TYPE_STAR, \haibao\app\model\data\Search::KEYWORD_TYPE_FASHION, '%'.$keyword.'%', '%'.$keyword.'%'
            ));
            
            $starId = $fashionId = array();
            while($search->fetch_assoc()){
                if($search->getData('TagType') == \haibao\app\model\data\Search::KEYWORD_TYPE_STAR){
                    array_push($starId, $search->getData('RecordId'));
                }
                if($search->getData('TagType') == \haibao\app\model\data\Search::KEYWORD_TYPE_FASHION){
                    array_push($fashionId, $search->getData('RecordId'));
                }
            }
            
            $joinArr = array();
            $whereArr = array('a.Title like %s');
            $paramArr = array('%'.$keyword.'%');
            if($starId){
                array_push($joinArr, 'left join ArticleStar as b on a.Id=b.ArticleId');
                $str = preg_replace('/(\d+)/', '%s', implode(',', $starId));
                array_push($whereArr, 'b.StarId in ('.$str.')');
                $paramArr = array_merge($paramArr, $starId);
            }
            if($fashionId){
                array_push($joinArr, 'left join ArticleFashion as c on a.Id=c.ArticleId');
                $str = preg_replace('/(\d+)/', '%s', implode(',', $fashionId));
                array_push($whereArr, 'c.FashionId in ('.$str.')');
                $paramArr = array_merge($paramArr, $fashionId);
            }
            
            $page = $page>=1 ? $page : 1;
            array_push($paramArr, ($page-1)*self::PAGE_SIZE);
            array_push($paramArr, self::PAGE_SIZE);
            $sql = 'select a.Id,a.Title,a.ImageId from Article as a '.implode(' ', $joinArr). ' where a.`Status`=1 and a.Published=1 and a.Type=1 and ('.implode(' or ', $whereArr).') group by a.Id order by a.Id desc limit %s,%s';
            $result = $this->query($sql, $paramArr);
            while ($result->fetch_assoc()){
                array_push($searchList, array(
                    'articleId' => $result->getData('Id'),
                    'title' => $result->getData('Title'),
                    'imageId' => $result->getData('ImageId')
                ));
            }
            $searchList && $cache->setSearchList($cacheKey, $searchList);
        }
        return $searchList;
    }
    
    /**
     * 取最近一段时间内的文章
     */
    public function getLeastArticleStar($datetime){
        $sql = 'select a.StarId,a.ArticleId,b.*,count(*) as cnt from ArticleStar as a left join ArticleProperty as b on a.ArticleId=b.ArticleId where a.ArticleId in (select Id from Article where Published=1 and `Status`=1 and PublishTime>=%s) group by a.StarId ';
        $result = $this->dbApp()->query($sql, array($datetime));
         
        $leastArticle = array();
        while ($row = $result->fetch_assoc()){
            array_push($leastArticle, $row);
        }
        return $leastArticle;
    }
    
    /**
     * 根据明星id查询明星中英文名
     */
    public function getStarByIds($starIds){
        if(!$starIds){
            return false;
        }
        $str = preg_replace('/(\d+)/', '%s', implode(',', $starIds));
        $sql = 'select Id,TagId,NameCn,NameEn from Celebrity where Id in ('.$str.') and Status=%s order by find_in_set(Id, "'.implode(',', $starIds).'")';
        array_push($starIds, \haibao\cms\model\data\Celebrity::STATUS_ENABLE);
        
        $result = $this->dbCms()->query($sql, $starIds);
        $retArr = array();
        while ($row = $result->fetch_assoc()) {
            array_push($retArr, $row);
        }
        return $retArr;
    }
    
    public function getHotStarListFromCache($key){
        $cache = new \haibao\app\cache\Search();
        return $cache->getHotStarList($key);
    }
    
    public function setHotStarListCache($key, $starList){
        $cache = new \haibao\app\cache\Search();
        $cache->setHotStarList($key, $starList);
    }
    
    /**
     * 添加搜索记录
     */
    private function saveSearchRecod($keyword){
        $this->dbApp()->query('insert into SearchRecord(`Keyword`, `CreateTime`) values(%s,%s)', array(
            $keyword, date('Y-m-d H:i:s')
        ));
    }
    
    private function dbCms(){
        $this->setConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_CMS);
        return $this;
    }
    
    private function dbApp(){
        $this->setConfig(\haibao\classlibrary\cms\Config::CLASSLIBRARY_CONFIG_MYSQL_HAIBAO_APP);
        return $this;
    }
    
}